package com.my.pdfexplorer.utils;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.my.pdfexplorer.BaseActivity;
import com.my.pdfexplorer.MainActivity;
import com.my.pdfexplorer.R;
import com.my.pdfexplorer.models.PopupWindowPdfPositionStatus;
import com.my.pdfexplorer.views.StatusView;
import com.snakeway.pdfviewer.annotation.base.MarkAreaType;
import com.snakeway.pdfviewer.model.MarkAreaInfo;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author snakeway
 * @description:
 * @date :2021/3/10 9:14
 */
public class PopupWindowUtil {
    public static final String POPUPWINDOWKEY = "popupWindowKey";

    public interface OnShowPopupWindowOperatingListener {

        boolean onSelect(PopupWindow popupWindow, View view, MarkAreaType markAreaType);

        boolean onCancelSelect(PopupWindow popupWindow, View view, MarkAreaType markAreaType);

        void clearPage(PopupWindow popupWindow, View view);

        void onDismiss(PopupWindow popupWindow, View view);

    }

    public interface OnShowPopupWindowSelectMarkListener {

        boolean onSelect(PopupWindow popupWindow, View view, MarkAreaType markAreaType);

        boolean onCancelSelect(PopupWindow popupWindow, View view, MarkAreaType markAreaType);

        void clearPage(PopupWindow popupWindow, View view);

        void onDismiss(PopupWindow popupWindow, View view);

    }


    public static void setPopupWindowTouchModal(PopupWindow popupWindow,
                                                boolean touchModal) {
        if (null == popupWindow) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            popupWindow.setTouchModal(touchModal);
            return;
        }
        Method method;
        try {
            method = PopupWindow.class.getDeclaredMethod("setTouchModal",
                    boolean.class);
            method.setAccessible(true);
            method.invoke(popupWindow, touchModal);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public interface OnShowPopupWindowBookMarketListener {

        void onClick(PopupWindow popupWindow, View view);

        void onDismiss(PopupWindow popupWindow, View view);

    }


    public interface OnShowPopupWindowInputListener {

        void onCancelClick(PopupWindow popupWindow, View view);

        void onOkClick(PopupWindow popupWindow, View view, String text);

        void onDismiss(PopupWindow popupWindow, View view);

    }

    public static PopupWindow showPopupWindowInput(final BaseActivity baseActivity, View view, final View needEnableView, final String title, final String defaultText, final OnShowPopupWindowInputListener onShowPopupWindowInputListener) {
        if (view.getWindowToken() == null) {
            return null;
        }
        if (needEnableView != null) {
            needEnableView.setEnabled(false);
        }
        LayoutInflater layoutInflater = baseActivity.getLayoutInflater();
        View popupWindowView = layoutInflater.inflate(R.layout.popupwindow_input, null);
        final String popupWindowKey = POPUPWINDOWKEY + TimeUtil.getOnlyTimeWithoutSleep();
        int popupWindowWidth = BaseActivity.getScreenWidth(baseActivity) * 2 / 3;
        final PopupWindow popupWindow = new PopupWindow(popupWindowView, popupWindowWidth, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams windowManagerLayoutParams = baseActivity.getWindow().getAttributes();
                windowManagerLayoutParams.alpha = 1.0f;
                baseActivity.getWindow().setAttributes(windowManagerLayoutParams);
                if (needEnableView != null) {
                    needEnableView.setEnabled(true);
                }
                if (onShowPopupWindowInputListener != null) {
                    onShowPopupWindowInputListener.onDismiss(popupWindow, popupWindowView);
                }
                baseActivity.removePopupWindow(popupWindowKey);
            }
        });
        final TextView textViewTitle = (TextView) popupWindowView.findViewById(R.id.textViewTitle);
        final EditText editText = (EditText) popupWindowView.findViewById(R.id.editText);
        final TextView textViewCancel = (TextView) popupWindowView.findViewById(R.id.textViewCancel);
        final TextView textViewOk = (TextView) popupWindowView.findViewById(R.id.textViewOk);
        textViewTitle.setText(title);
        editText.setText(defaultText);
        editText.setSelection(defaultText.length());
        textViewCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onShowPopupWindowInputListener != null) {
                    onShowPopupWindowInputListener.onCancelClick(popupWindow, popupWindowView);
                }
            }
        });
        textViewOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onShowPopupWindowInputListener != null) {
                    onShowPopupWindowInputListener.onOkClick(popupWindow, popupWindowView, editText.getText().toString());
                }
            }
        });

        ColorDrawable colorDrawable = new ColorDrawable(Color.argb(0, 255, 255, 255));
        popupWindow.setBackgroundDrawable(colorDrawable);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setAnimationStyle(R.style.popwindowNormalAnimationCenter);
        WindowManager.LayoutParams windowManagerLayoutParams = baseActivity.getWindow().getAttributes();
        windowManagerLayoutParams.alpha = 0.7f;
        baseActivity.getWindow().setAttributes(windowManagerLayoutParams);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
        baseActivity.addPopupWindow(popupWindowKey, popupWindow);
        return popupWindow;
    }


    public interface OnShowPopupWindowBottomInputListener {

        void onCancelClick(PopupWindow popupWindow, View view);

        void onOkClick(PopupWindow popupWindow, View view, String text);

        void onDismiss(PopupWindow popupWindow, View view);

    }

    public static PopupWindow showPopupWindowBottomInput(final BaseActivity baseActivity, View view, final View needEnableView, final String title, final String defaultText, final OnShowPopupWindowBottomInputListener onShowPopupWindowBottomInputListener) {
        if (view.getWindowToken() == null) {
            return null;
        }
        if (needEnableView != null) {
            needEnableView.setEnabled(false);
        }
        LayoutInflater layoutInflater = baseActivity.getLayoutInflater();
        View popupWindowView = layoutInflater.inflate(R.layout.popupwindow_bottom_input, null);
        final String popupWindowKey = POPUPWINDOWKEY + TimeUtil.getOnlyTimeWithoutSleep();
        int popupWindowHeight = BaseActivity.getScreenHeight(baseActivity) * 3 / 5;
        final PopupWindow popupWindow = new PopupWindow(popupWindowView, ViewGroup.LayoutParams.MATCH_PARENT, popupWindowHeight);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams windowManagerLayoutParams = baseActivity.getWindow().getAttributes();
                windowManagerLayoutParams.alpha = 1.0f;
                baseActivity.getWindow().setAttributes(windowManagerLayoutParams);
                if (needEnableView != null) {
                    needEnableView.setEnabled(true);
                }
                if (onShowPopupWindowBottomInputListener != null) {
                    onShowPopupWindowBottomInputListener.onDismiss(popupWindow, popupWindowView);
                }
                baseActivity.removePopupWindow(popupWindowKey);
            }
        });
        final TextView textViewTitle = (TextView) popupWindowView.findViewById(R.id.textViewTitle);
        final EditText editText = (EditText) popupWindowView.findViewById(R.id.editText);
        final TextView textViewCancel = (TextView) popupWindowView.findViewById(R.id.textViewCancel);
        final TextView textViewOk = (TextView) popupWindowView.findViewById(R.id.textViewOk);
        textViewTitle.setText(title);
        editText.setText(defaultText);
        editText.setSelection(defaultText.length());
//        editText.post(new Runnable() {
//            @Override
//            public void run() {
//                InputMethodManager im = (InputMethodManager)baseActivity
//                        .getSystemService(Context.INPUT_METHOD_SERVICE);
//                im.showSoftInput(editText, 0);
//            }
//        });
        textViewCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onShowPopupWindowBottomInputListener != null) {
                    onShowPopupWindowBottomInputListener.onCancelClick(popupWindow, popupWindowView);
                }
            }
        });
        textViewOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onShowPopupWindowBottomInputListener != null) {
                    onShowPopupWindowBottomInputListener.onOkClick(popupWindow, popupWindowView, editText.getText().toString());
                }
            }
        });
        ColorDrawable colorDrawable = new ColorDrawable(Color.argb(0, 255, 255, 255));
        popupWindow.setBackgroundDrawable(colorDrawable);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setAnimationStyle(R.style.popwindowNormalAnimation);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        WindowManager.LayoutParams windowManagerLayoutParams = baseActivity.getWindow().getAttributes();
        windowManagerLayoutParams.alpha = 0.7f;
        baseActivity.getWindow().setAttributes(windowManagerLayoutParams);
        popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
        baseActivity.addPopupWindow(popupWindowKey, popupWindow);
        return popupWindow;
    }


    public static PopupWindow showPopupWindowSelectMark(final BaseActivity baseActivity, View view, final View needEnableView, final String key, final PopupWindowPdfPositionStatus popupWindowPdfPositionStatus, final List<MarkAreaType> selectMarkAreaTypes, int selectMarkPenModeIndex, MarkAreaInfo markAreaInfo, final OnShowPopupWindowSelectMarkListener onShowPopupWindowSelectMarkListener, OnSelectMarkPenModeListener onSelectMarkPenModeListener) {
        if (view.getWindowToken() == null || popupWindowPdfPositionStatus == null) {
            return null;
        }
        if (needEnableView != null) {
            needEnableView.setEnabled(false);
        }
        LayoutInflater layoutInflater = baseActivity.getLayoutInflater();
        View popupWindowView = layoutInflater.inflate(R.layout.popupwindow_select_mark, null);
        final String popupWindowKey = key != null ? key : (POPUPWINDOWKEY + TimeUtil.getOnlyTimeWithoutSleep());
        final PopupWindow popupWindow = new PopupWindow(popupWindowView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        setPopupWindowTouchModal(popupWindow, false);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (needEnableView != null) {
                    needEnableView.setEnabled(true);
                }
                if (onShowPopupWindowSelectMarkListener != null) {
                    onShowPopupWindowSelectMarkListener.onDismiss(popupWindow, popupWindowView);
                }
                baseActivity.removePopupWindow(popupWindowKey);
            }
        });

        final LinearLayout linearLayoutMarkMode = (LinearLayout) popupWindowView.findViewById(R.id.linearLayoutMarkMode);

        final StatusView statusViewCopy = (StatusView) popupWindowView.findViewById(R.id.statusViewCopy);
        final StatusView statusViewMarkMode = (StatusView) popupWindowView.findViewById(R.id.statusViewMarkMode);
        final StatusView statusViewAnnotation = (StatusView) popupWindowView.findViewById(R.id.statusViewAnnotation);
        final FrameLayout frameLayoutHighLight = (FrameLayout) popupWindowView.findViewById(R.id.frameLayoutHighLight);
        final FrameLayout frameLayoutWaveLine = (FrameLayout) popupWindowView.findViewById(R.id.frameLayoutWaveLine);
        final FrameLayout frameLayoutUnderLine = (FrameLayout) popupWindowView.findViewById(R.id.frameLayoutUnderLine);
        final StatusView statusViewHighLight = (StatusView) popupWindowView.findViewById(R.id.statusViewHighLight);
        final StatusView statusViewWaveLine = (StatusView) popupWindowView.findViewById(R.id.statusViewWaveLine);
        final StatusView statusViewUnderLine = (StatusView) popupWindowView.findViewById(R.id.statusViewUnderLine);

        boolean isSelect = false;
        statusViewCopy.setTag(markAreaInfo);

        if (selectMarkAreaTypes != null) {
            for (MarkAreaType markAreaType : selectMarkAreaTypes) {
                if (markAreaType == MarkAreaType.HIGHLIGHT || markAreaType == MarkAreaType.UNDERWAVELINE || markAreaType == MarkAreaType.UNDERLINE || markAreaType == MarkAreaType.DELETELINE) {
                    isSelect = true;
                }
                switch (markAreaType) {
                    case HIGHLIGHT:
                        statusViewHighLight.setChecked(true);
                        break;
                    case UNDERWAVELINE:
                        statusViewWaveLine.setChecked(true);
                        break;
                    case UNDERLINE:
                        statusViewUnderLine.setChecked(true);
                        break;
                    default:
                        break;
                }
            }
        }
        updateStatusViewMarkMode(baseActivity, view, popupWindow, popupWindowView, popupWindowPdfPositionStatus, linearLayoutMarkMode, statusViewMarkMode, isSelect);
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                StatusView statusView = null;
                MarkAreaType markAreaType = null;
                switch (view.getId()) {
                    case R.id.frameLayoutHighLight:
                        statusView = statusViewHighLight;
                        markAreaType = MarkAreaType.HIGHLIGHT;
                        break;
                    case R.id.frameLayoutWaveLine:
                        statusView = statusViewWaveLine;
                        markAreaType = MarkAreaType.UNDERWAVELINE;
                        break;
                    case R.id.frameLayoutUnderLine:
                        statusView = statusViewUnderLine;
                        markAreaType = MarkAreaType.UNDERLINE;
                        break;
                    case R.id.statusViewCopy:
                        MarkAreaInfo theStatusViewCopy = (MarkAreaInfo) statusViewCopy.getTag();
                        if (theStatusViewCopy != null) {
                            StringUtil.copyToClipboard(baseActivity, theStatusViewCopy.getText());
                        }
                        ToastUtil.showShortToast(baseActivity, baseActivity.getString(R.string.copy_success));
                        break;
                    case R.id.statusViewMarkMode:
                        boolean isOpen = linearLayoutMarkMode.getTag() != null && (boolean) linearLayoutMarkMode.getTag();
                        if (!isOpen) {
                            updateStatusViewMarkMode(baseActivity, view, popupWindow, popupWindowView, popupWindowPdfPositionStatus, linearLayoutMarkMode, statusViewMarkMode, true);
                        } else {
                            if (statusViewHighLight.isChecked()) {
                                boolean result = onShowPopupWindowSelectMarkListener.onCancelSelect(popupWindow, view, MarkAreaType.HIGHLIGHT);
                                if (result) {
                                    statusViewHighLight.setChecked(!statusViewHighLight.isChecked());
                                }
                            }
                            if (statusViewWaveLine.isChecked()) {
                                boolean result = onShowPopupWindowSelectMarkListener.onCancelSelect(popupWindow, view, MarkAreaType.UNDERWAVELINE);
                                if (result) {
                                    statusViewWaveLine.setChecked(!statusViewWaveLine.isChecked());
                                }
                            }
                            if (statusViewUnderLine.isChecked()) {
                                boolean result = onShowPopupWindowSelectMarkListener.onCancelSelect(popupWindow, view, MarkAreaType.UNDERLINE);
                                if (result) {
                                    statusViewUnderLine.setChecked(!statusViewUnderLine.isChecked());
                                }
                            }
                        }
                        break;
                    default:
                        return;
                }
                if (statusView != null) {
                    if (MainActivity.SELECT_AREA_MARK_SINGLE) {
                        statusViewHighLight.setChecked(false);
                        statusViewWaveLine.setChecked(false);
                        statusViewUnderLine.setChecked(false);
                        statusView.setChecked(true);
                        if (selectMarkAreaTypes != null) {
                            for (int i = 0; i < selectMarkAreaTypes.size(); i++) {
                                MarkAreaType selectMarkAreaType = selectMarkAreaTypes.get(i);
                                onShowPopupWindowSelectMarkListener.onCancelSelect(popupWindow, view, selectMarkAreaType);
                            }
                        }
                        onShowPopupWindowSelectMarkListener.onSelect(popupWindow, view, markAreaType);
                    } else {
                        boolean isChecked = statusView.isChecked();
                        boolean result = false;
                        if (isChecked) {
                            result = onShowPopupWindowSelectMarkListener.onCancelSelect(popupWindow, view, markAreaType);
                        } else {
                            result = onShowPopupWindowSelectMarkListener.onSelect(popupWindow, view, markAreaType);
                        }
                        if (result) {
                            statusView.setChecked(!isChecked);
                        }
                    }
                }
            }
        };
        frameLayoutHighLight.setOnClickListener(onClickListener);
        frameLayoutWaveLine.setOnClickListener(onClickListener);
        frameLayoutUnderLine.setOnClickListener(onClickListener);
        statusViewCopy.setOnClickListener(onClickListener);
        statusViewMarkMode.setOnClickListener(onClickListener);

        setMarkPenModeOnClickListener(popupWindowView, selectMarkPenModeIndex, onSelectMarkPenModeListener, selectMarkAreaTypes);

        int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        popupWindowView.measure(spec, spec);
        int measuredWidth = popupWindowView.getMeasuredWidth();
        int measuredHeight = popupWindowView.getMeasuredHeight();

        ColorDrawable colorDrawable = new ColorDrawable(Color.argb(0, 255, 255, 255));
        popupWindow.setBackgroundDrawable(colorDrawable);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setAnimationStyle(R.style.popwindowNormalAnimationCenter);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        if (popupWindowPdfPositionStatus.isUp()) {
            popupWindow.showAtLocation(view, Gravity.LEFT | Gravity.TOP, popupWindowPdfPositionStatus.getX() - measuredWidth / 2, popupWindowPdfPositionStatus.getY());
        } else {
            popupWindow.showAtLocation(view, Gravity.LEFT | Gravity.TOP, popupWindowPdfPositionStatus.getX() - measuredWidth / 2, popupWindowPdfPositionStatus.getY() - measuredHeight);
        }
        baseActivity.addPopupWindow(popupWindowKey, popupWindow);
        return popupWindow;
    }

    public static void cancelAllSelectMarks(List<MarkAreaType> selectMarkAreaTypes) {

    }

    public static void updateStatusViewMarkMode(BaseActivity baseActivity, View view, PopupWindow popupWindow, View popupWindowView, PopupWindowPdfPositionStatus popupWindowPdfPositionStatus, LinearLayout linearLayoutMarkMode, StatusView statusViewMarkMode, boolean openMarkMode) {
        if (openMarkMode) {
            linearLayoutMarkMode.setVisibility(View.VISIBLE);
            statusViewMarkMode.setCheckImage(R.mipmap.select_mark_line_select);
            statusViewMarkMode.setUnCheckImage(R.mipmap.select_mark_line_select);
            statusViewMarkMode.getText().setText(baseActivity.getString(R.string.popupwindow_select_mark_delete_draw_line));
            linearLayoutMarkMode.setTag(true);
        } else {
            linearLayoutMarkMode.setVisibility(View.GONE);
            statusViewMarkMode.setCheckImage(R.mipmap.select_mark_line_unselect);
            statusViewMarkMode.setUnCheckImage(R.mipmap.select_mark_line_unselect);
            statusViewMarkMode.getText().setText(baseActivity.getString(R.string.popupwindow_select_mark_draw_line));
            linearLayoutMarkMode.setTag(false);
        }
        int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        popupWindowView.measure(spec, spec);
        int measuredWidth = popupWindowView.getMeasuredWidth();
        int measuredHeight = popupWindowView.getMeasuredHeight();
        if (popupWindowPdfPositionStatus.isUp()) {
            popupWindow.update(popupWindowPdfPositionStatus.getX() - measuredWidth / 2, popupWindowPdfPositionStatus.getY(), measuredWidth, measuredHeight);
        } else {
            popupWindow.update(popupWindowPdfPositionStatus.getX() - measuredWidth / 2, popupWindowPdfPositionStatus.getY() - measuredHeight, measuredWidth, measuredHeight);
        }
    }

    public static void setMarkPenModeOnClickListener(View contentView, int selectMarkPenModeIndex, OnSelectMarkPenModeListener onSelectMarkPenModeListener, List<MarkAreaType> selectMarkAreaTypes) {
        final FrameLayout frameLayoutMode1 = (FrameLayout) contentView.findViewById(R.id.frameLayoutMode1);
        final FrameLayout frameLayoutMode2 = (FrameLayout) contentView.findViewById(R.id.frameLayoutMode2);
        final FrameLayout frameLayoutMode3 = (FrameLayout) contentView.findViewById(R.id.frameLayoutMode3);
        final FrameLayout frameLayoutMode4 = (FrameLayout) contentView.findViewById(R.id.frameLayoutMode4);
        final FrameLayout frameLayoutMode5 = (FrameLayout) contentView.findViewById(R.id.frameLayoutMode5);
        final TextView textViewMode1Select = (TextView) contentView.findViewById(R.id.textViewMode1Select);
        final TextView textViewMode2Select = (TextView) contentView.findViewById(R.id.textViewMode2Select);
        final TextView textViewMode3Select = (TextView) contentView.findViewById(R.id.textViewMode3Select);
        final TextView textViewMode4Select = (TextView) contentView.findViewById(R.id.textViewMode4Select);
        final TextView textViewMode5Select = (TextView) contentView.findViewById(R.id.textViewMode5Select);

        frameLayoutMode1.setTag(0);
        frameLayoutMode2.setTag(1);
        frameLayoutMode3.setTag(2);
        frameLayoutMode4.setTag(3);
        frameLayoutMode5.setTag(4);

        List<FrameLayout> frameLayoutModes = new ArrayList<>();
        List<TextView> textViewModes = new ArrayList<>();
        frameLayoutModes.add(frameLayoutMode1);
        frameLayoutModes.add(frameLayoutMode2);
        frameLayoutModes.add(frameLayoutMode3);
        frameLayoutModes.add(frameLayoutMode4);
        frameLayoutModes.add(frameLayoutMode5);
        textViewModes.add(textViewMode1Select);
        textViewModes.add(textViewMode2Select);
        textViewModes.add(textViewMode3Select);
        textViewModes.add(textViewMode4Select);
        textViewModes.add(textViewMode5Select);
        for (int i = 0; i < frameLayoutModes.size(); i++) {
            int theI = i;
            final FrameLayout fragment = frameLayoutModes.get(i);
            final TextView textView = textViewModes.get(i);
            if (selectMarkPenModeIndex == i) {
                textView.setVisibility(View.VISIBLE);
            } else {
                textView.setVisibility(View.GONE);
            }
            frameLayoutModes.get(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (TextView textViewMode : textViewModes) {
                        textViewMode.setVisibility(View.GONE);
                    }
                    textView.setVisibility(View.VISIBLE);
                    onSelectMarkPenModeListener.onClick(fragment, selectMarkAreaTypes, theI);
                }
            });
        }
    }


    public interface OnSelectMarkPenModeListener {
        void onClick(View view, List<MarkAreaType> selectMarkAreaTypes, int index);
    }
}
